package com.joysuch.wwyt.edu.controller;


import cn.zlg.common.springmvc.validate.constraints.NotNull;
import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.JsonUtil;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateQueryParam;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateUserBean;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateUserVo;
import com.joysuch.wwyt.edu.entity.EduCertificateNotify;
import com.joysuch.wwyt.edu.entity.WwytEduCertificateUser;
import com.joysuch.wwyt.edu.enums.CertStatus;
import com.joysuch.wwyt.edu.service.EduCertificateNotifyService;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import com.joysuch.wwyt.workflow.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pp
 * @since 2021-04-15
 */
@RestController
@RequestMapping("/edu/cartificate/user/v2")
@Api(tags = "证书-持证管理")
public class WwytEduCertificateUserController {
    @Autowired
    private WwytEduCertificateUserService wwytEduCertificateUserService;

    @Autowired
    private EduCertificateNotifyService eduCertificateNotifyService;

    @RequiresPermissions("edu:cartificate:user:v2:add")
    @PostMapping("add")
    @ApiOperation("添加持证人员")
    public ResultBean add(@Valid @RequestBody WwytEduCertificateUserBean entity) {
        //上传附件处理
        if (!CollectionUtils.isEmpty(entity.getAttachmentBeans())) {
            List<Long> attchIds = entity.getAttachmentBeans().stream().map(BaseAttachmentBean::getId).collect(Collectors.toList());
            entity.setAttachmentIdJson(JsonUtil.toJson(attchIds));
        }
        wwytEduCertificateUserService.insert(entity);
        return ResultBean.success("添加成功");
    }

    //    @RequiresPermissions("edu:cartificate:user:v2:getOne")
    @GetMapping("getOne")
    @ApiOperation("查询单条")
    public ResultBean getOne(@NotNull(message = "id不能为空") Long id) {
        WwytEduCertificateUserVo vo = wwytEduCertificateUserService.findOne(id);
        return ResultBean.success(vo);
    }

    //    @RequiresPermissions("edu:cartificate:user:v2:page")
    @PostMapping("page")
    @ApiOperation("分页查询")
    public ResultBean page(@Valid @RequestBody WwytEduCertificateQueryParam param) {
        return wwytEduCertificateUserService.findPage(param);

    }

    @RequiresPermissions("edu:cartificate:user:v2:update")
    @PostMapping("update")
    @ApiOperation("更新")
    public ResultBean update(@Valid @RequestBody WwytEduCertificateUserBean entity) {
        if (entity.getId() == null) {
            throw new IllegalArgumentException("人员id不能为空");
        }
        Integer aheadDays=0;
        EduCertificateNotify notify = eduCertificateNotifyService.findByCertId(entity.getCertId());
        if (notify!=null){
            aheadDays=notify.getAheadDays();
        }
        if (entity.getOutOfDateTime() != null) {
            //即将过期

            if ((entity.getOutOfDateTime().after(new Date())||
                    com.joysuch.wwyt.util.DateUtils.getStartOfDay(entity.getOutOfDateTime()).equals(com.joysuch.wwyt.util.DateUtils.getStartOfDay(new Date())))
                    && entity.getOutOfDateTime().before(DateUtils.addDays(new Date(), aheadDays))) {
                entity.setCertStatus(CertStatus.EXPIRING_SOON.status.toString());
            } else if (entity.getOutOfDateTime().after(new Date()) &&(entity.getTakenTime()==null||entity.getTakenTime().before(new Date())) ) {
                //有效
                entity.setCertStatus(CertStatus.EFFECTIVE.status.toString());
            }  else if (entity.getOutOfDateTime().before(new Date())) {
                //过期
                entity.setCertStatus(CertStatus.EXPIRED.status.toString());
            } else {
                entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
            }
        } else {
            entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
        }
        if (!CollectionUtils.isEmpty(entity.getAttachmentBeans())) {
            List<Long> attchIds = entity.getAttachmentBeans().stream().map(BaseAttachmentBean::getId).collect(Collectors.toList());
            entity.setAttachmentIdJson(JsonUtil.toJson(attchIds));
        } else {
            //如果更新附件为空
            WwytEduCertificateUserVo one = wwytEduCertificateUserService.findOne(entity.getId());
            if (!StringUtils.isEmpty(one.getAttachmentIdJson())) {
                entity.setAttachmentIdJson(null);
            }
        }
        //一个证书种类的只能有一个唯一编号
        LambdaQueryWrapper<WwytEduCertificateUser> repeat = new QueryWrapper<WwytEduCertificateUser>().lambda()
                .ne(WwytEduCertificateUser::getId, entity.getId())
                .eq(WwytEduCertificateUser::getCertId, entity.getCertId())
                .eq(WwytEduCertificateUser::getCertNo, entity.getCertNo())
                .eq(WwytEduCertificateUser::getDeleteFlag, "0");
        List<WwytEduCertificateUser> list = wwytEduCertificateUserService.list(repeat);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new IllegalArgumentException("证书编号重复! 一个证书种类的只能有一个唯一编号!");
        }
        entity.setUpdateTime(new Date());
        wwytEduCertificateUserService.saveOrUpdate(entity);
        return ResultBean.success("修改成功");
    }

    @RequiresPermissions("edu:cartificate:user:v2:delete")
    @PostMapping("delete")
    @ApiOperation("批量删除")
    public ResultBean delete(@NotEmpty(message = "请勾选删除项") @RequestBody List<Long> ids) {
        wwytEduCertificateUserService.removeByIds(ids);
        return ResultBean.success("删除成功");
    }
}

